﻿using DBService.DataHelper;
using Entity;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBService.Handler
{
  public  class DbBase
    {
      DbHelper helper;
      public DbBase()
      {
          helper = new DbHelper();
      }
      string DbName = "protest";
        #region 判断数据库中，指定表是否存在
        /// <summary>
        /// 判断数据库表是否存在
        /// </summary>
        /// <param name="db">数据库</param>
        /// <param name="tb">数据表名</param>
        /// <param name="connKey">连接数据库的key</param>
        /// <returns>true:表示数据表已经存在；false，表示数据表不存在</returns>
        public Boolean IsTableExist(string tableName)
        {

            string createDbStr = "use protest select 1 from  sysobjects where  id = object_id('" + tableName + "') and type = 'U'";

            //在指定的数据库中  查找 该表是否存在
            var ds= helper.ExecuteDataSet(createDbStr, null, CommandType.Text);
     
            if (ds.Tables[0] .Rows.Count<1 || int.Parse(ds.Tables[0] .Rows[0][0].ToString())<1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion
        public ReturnResult CreateDataTable(string tableName, Dictionary<string, string> dic)
        {

            //如果数据库表存在，则抛出错误
            if (IsTableExist(tableName))
            {
                throw new Exception("数据库表已经存在！");
            }
            else//数据表不存在，创建数据表
            {
                //拼接字符串，（该串为创建内容）
                string content = "serial int identity(1,1) primary key ";
                //取出dic中的内容，进行拼接
                List<string> test = new List<string>(dic.Keys);
                for (int i = 0; i < dic.Count(); i++)
                {
                    content = content + " , " + test[i] + " " + dic[test[i]];
                }

                //其后判断数据表是否存在，然后创建数据表
                string createTableStr = "use " + DbName + " create table " + tableName + " (" + content + ")";

                return  helper.ExecuteNonQuery(createTableStr,null,CommandType.Text);
            }
        }

    }
}
